package cn.edu.jxau.core.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 异步返回各种格式
 * json
 * xml
 * text
 * file
 * @Author Mangodai
 * @Date 8/23/2017 2:55 PM
 *
 */
public class ResponseUtils {

    /**
     * 发送内容
     * @param response
     * @param contentType
     * @param text
     */
    public static void render(HttpServletResponse response, String contentType, String text){
        response.setContentType(contentType);
        try {
            response.getWriter().write(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //发送的是JSON
    public static void renderJson(HttpServletResponse response,String text){
        render(response, "application/json;charset=UTF-8", text);
    }
    //发送xml
    public static void renderXml(HttpServletResponse response,String text){
        render(response, "text/xml;charset=UTF-8", text);
    }
    //发送text
    public static void renderText(HttpServletResponse response,String text){
        render(response, "text/plain;charset=UTF-8", text);
    }

    /**
     * response 下载数据，给一个绝对路径
     * @param file 文件下载
     * @param response
     */
    public static void download(File file, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String(filename.getBytes("GBK"), "ISO-8859-1"));
            String contentType = request.getSession().getServletContext().getMimeType(filename);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(
                    response.getOutputStream());
            response.setContentType(contentType);
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}
